package com.wuliu.driver.util;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
@Component
public class ReverseGeocodingExample {

    private static final String GAODE_API_KEY = "a2b6275dc0cc92d483a3cb8478d60f33";
    private static final String REVERSE_GEOCODING_URL = "https://restapi.amap.com/v3/geocode/regeo";
    private static final String GEOCODING_URL = "https://restapi.amap.com/v3/geocode/geo";
    @Autowired
    private MapUtil mapUtil;

    public static void main(String[] args) throws IOException {
        String address = "山西省太原市小店区平阳路街道平阳南路57号小马幼儿园";
        OkHttpClient client = new OkHttpClient();

        String url = String.format("%s?address=%s&output=json&key=%s",
                GEOCODING_URL, address, GAODE_API_KEY);

        Request request = new Request.Builder()
                .url(url)
                .build();
        String jsonResult = "";
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }

            jsonResult = response.body().string();
        }
        try {
            JSONObject jsonObject = new JSONObject(jsonResult);
            int status = jsonObject.optInt("status");
            if (status == 1) { // 成功
                JSONArray geocodes = jsonObject.getJSONArray("geocodes");
                if (geocodes.length() > 0) {
                    JSONObject geocode = geocodes.getJSONObject(0);
                    String formattedAddress = geocode.getString("formatted_address");

                    // 正确解析 location 字段
                    String locationStr = geocode.getString("location");
                    String[] locationParts = locationStr.split(",");
                    if (locationParts.length == 2) {
                        double longitude = Double.parseDouble(locationParts[0]);
                        double latitude = Double.parseDouble(locationParts[1]);

                        System.out.println("Formatted Address: " + formattedAddress);
                        System.out.println("Longitude: " + longitude);
                        System.out.println("Latitude: " + latitude);
                    } else {
                        System.out.println("Invalid location format: " + locationStr);
                    }
                } else {
                    System.out.println("No geocoding results found.");

                }
            } else {
                System.out.println("Error: " + jsonObject.optString("info"));

            }
        } catch (Exception e) {
            e.printStackTrace();

        }
    }


    public static String reverseGeocode(double latitude, double longitude) throws IOException {
        OkHttpClient client = new OkHttpClient();

        String url = String.format("%s?location=%.6f,%.6f&output=json&key=%s",
                REVERSE_GEOCODING_URL, longitude, latitude, GAODE_API_KEY);

        Request request = new Request.Builder()
                .url(url)
                .build();
        System.out.println(url);

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }

            return response.body().string();
        }
    }

    public static void parseResult(String jsonResult) {
        try {
            JSONObject jsonObject = new JSONObject(jsonResult);
            int status = jsonObject.optInt("status");
            if (status == 1) { // 成功

                JSONObject regeocode = jsonObject.getJSONObject("regeocode");
                JSONObject addressComponent = regeocode.getJSONObject("addressComponent");

                String formattedAddress = regeocode.getString("formatted_address");
                String province = addressComponent.getString("province");
                String city = addressComponent.getString("city");
                String district = addressComponent.getString("district");
                String town = addressComponent.getString("township");
                //String street = addressComponent.getString("street");

                System.out.println("Formatted Address: " + formattedAddress);
                System.out.println("Province: " + province);
                System.out.println("City: " + city);
                System.out.println("District: " + district);
                System.out.println("Town: " + town);
                //System.out.println("Street: " + street);
            } else {
                System.out.println("Error: " + jsonObject.optString("info"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
